#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
import re
from typing import Dict, Any
from .parser import TableInfo, Column
from src.base.registry import bera

class SQLToJSONConverter:
    """SQL转JSON配置转换器"""

    def __init__(self):
        self.type_mapping = {
            'VARCHAR': 'text',
            'CHAR': 'text',
            'TEXT': 'text',
            'INT': 'number',
            'BIGINT': 'number',
            'TINYINT': 'number',
            'DECIMAL': 'number',
            'DATETIME': 'datetime',
            'DATE': 'date',
            'TIMESTAMP': 'datetime'
        }

    def _infer_mock_rule(self, column: Column) -> str:
        """推断模拟数据规则"""
        if column.auto_increment:
            return 'auto_increment'

        name = column.name.lower()
        if 'name' in name:
            return 'chinese_name'
        elif 'date' in name:
            return 'date_range(2020-01-01,2024-12-31)'
        elif column.type == 'TINYINT' and column.comment and ('状态' in column.comment or '类型' in column.comment):
            return 'enum'
        elif name.endswith('_no') or name.endswith('_code'):
            return f'prefix_{name.split("_")[0].upper()}{{6}}'

        return ''

    def _extract_enum_mapping(self, comment: str) -> str:
        """从注释中提取枚举值映射"""
        if not comment:
            return ''

        # 匹配类似 "状态：1-启用，2-禁用" 的格式
        enum_pattern = r'[：:]\s*(\d+[-_]\w+(?:\s*[,，]\s*\d+[-_]\w+)*)'
        match = re.search(enum_pattern, comment)
        if match:
            mappings = match.group(1).split(',')
            return ';'.join(m.strip().replace('，', '') for m in mappings)

        return ''

    def _to_camel_case(self, name: str) -> str:
        """转换为驼峰命名"""
        parts = name.split('_')
        return parts[0] + ''.join(p.capitalize() for p in parts[1:])

    def _to_pascal_case(self, name: str) -> str:
        """转换为帕斯卡命名"""
        return ''.join(p.capitalize() for p in name.split('_'))

    def convert(self, table_info: TableInfo) -> Dict[str, Any]:
        """转换表信息为配置格式"""
        if self.verbose:
            bera.logger.debug(f"开始转换字段，共 {len(table_info.columns)} 个字段")

        config = {
            "table_info": {
                "chinese_name": table_info.comment or table_info.name,
                "table_name": table_info.name,
                "entity_name": self._to_camel_case(table_info.name.split('_')[-1]),
                "class_name": self._to_pascal_case(table_info.name.split('_')[-1]),
                "java_package_name": "com.example.miaoma"
            },
            "columns": []
        }

        for column in table_info.columns:
            if self.verbose:
                bera.logger.debug(f"处理字段: {column.name}, 类型: {column.type}")
            
            field_type = self.type_mapping.get(column.type, 'text')

            # 处理特殊类型
            if column.type == 'TINYINT' and column.comment and ('状态' in column.comment or '类型' in column.comment):
                field_type = 'select'

            column_config = {
                "字段中文名": column.comment.split('，')[0] if column.comment else column.name,
                "字段名称": column.name,
                "字段类型": field_type,
                "是否可为空": str(column.nullable).lower(),
                "是否显示": "true",
                "是否可编辑": "true" if not column.auto_increment else "false",
                "模拟规则": self._infer_mock_rule(column),
                "值映射关系": self._extract_enum_mapping(column.comment or ""),
                "字段备注": column.comment or ""
            }

            if self.verbose:
                bera.logger.debug(f"字段配置: {column_config}")

            config["columns"].append(column_config)

        return config

class JSONToSQLConverter:
    """JSON配置转SQL转换器"""

    def __init__(self):
        self.type_mapping = {
            'text': 'VARCHAR(255)',
            'number': 'INT',
            'datetime': 'DATETIME',
            'date': 'DATE',
            'select': 'TINYINT'
        }

    def _get_column_type(self, field_type: str, column: Dict[str, Any]) -> str:
        """获取字段类型定义"""
        base_type = self.type_mapping.get(field_type, 'VARCHAR(255)')

        # 处理特殊类型
        if field_type == 'text' and column.get('字段备注', '').lower().find('text') != -1:
            return 'TEXT'

        return base_type

    def convert(self, json_content: str) -> str:
        """转换为SQL"""
        config = json.loads(json_content)
        table_info = config['table_info']
        columns = config['columns']

        sql_parts = [
            f"CREATE TABLE `{table_info['table_name']}` ("
        ]

        # 添加字段定义
        for column in columns:
            column_def = [
                f"  `{column['字段名称']}`",
                self._get_column_type(column['字段类型'], column)
            ]

            if column['是否可为空'] == 'false':
                column_def.append('NOT NULL')

            if column.get('模拟规则') == 'auto_increment':
                column_def.append('AUTO_INCREMENT')

            if column.get('字段备注'):
                column_def.append(f"COMMENT '{column['字段备注']}'")

            sql_parts.append(' '.join(column_def) + ',')

        # 添加主键
        primary_key = next((col['字段名称'] for col in columns if col.get('模拟规则') == 'auto_increment'), None)
        if primary_key:
            sql_parts.append(f"  PRIMARY KEY (`{primary_key}`),")

        # 删除最后一个逗号
        sql_parts[-1] = sql_parts[-1].rstrip(',')

        # 添加表选项
        sql_parts.append(f") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='{table_info['chinese_name']}';")

        return '\n'.join(sql_parts)